package com.ms.oschina.adapter;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.ms.oschina.R;
import com.ms.oschina.util.UiUtils;
import com.ms.oschina.view.PagerSlidingTabStrip;

public class ViewPagerFragmentAdapter extends FragmentStatePagerAdapter {

	private List<ViewPagerInfo> infos = new ArrayList<ViewPagerFragmentAdapter.ViewPagerInfo>();
	private String[] mTitles;
	private PagerSlidingTabStrip psts;

	public ViewPagerFragmentAdapter(FragmentManager fragmentManager,
			ViewPager pagerContent, PagerSlidingTabStrip pstGroupTabs) {
		super(fragmentManager);
		this.psts = pstGroupTabs;
		pagerContent.setAdapter(this);
		pstGroupTabs.setViewPager(pagerContent);
	}

	@Override
	public int getCount() {
		return infos.size();
	}


	/**
	 * 得到每一个item显示的fragment
	 */
	@Override
	public Fragment getItem(int position) {
		// 创建fragment
		// 使用fragmen工厂，去生成fragment。
		ViewPagerInfo viewPagerInfo = infos.get(position);
		return Fragment.instantiate(UiUtils.getContext(),
				viewPagerInfo.class1.getName(), viewPagerInfo.args);// 实例化一个fragment
	}

	public void addTab(String title, Class<? extends Fragment> class1,
			Bundle args) {
		ViewPagerInfo viewPagerInfo = new ViewPagerInfo(class1, args, title);
		infos.add(viewPagerInfo);
		addFragment(viewPagerInfo);
		notifyDataSetChanged();
	}

	private void addFragment(ViewPagerInfo info) {
		if (info == null) {
			return;
		}
		// 加入tab title
		View v = UiUtils.inflate(R.layout.base_viewpage_fragment_tab_item);
		TextView title = (TextView) v.findViewById(R.id.tab_title);
		title.setText(info.title);
		psts.addTab(v);
	}

	private class ViewPagerInfo {
		public ViewPagerInfo(Class<? extends Fragment> class1, Bundle args,
				String title) {
			this.class1 = class1;
			this.args = args;
			this.title = title;
		}

		String title;
		Class<? extends Fragment> class1;
		Bundle args;
	}

}
